import "./index.less";
import PatientInformation from "@/components/ViewComponents/PatientInformation/index";
import { useRef, useState, useEffect } from "react";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { useTranslation } from "react-i18next";
import { Button, message, Tag } from "antd";
import { BasicTable, useTable, BasicColumn, useRender } from "@/components/Table";
import { servicesPage, servicesPatientPage, diagnosisCreate, patServicesBatchcreate } from "@/api/SecondmentDictionary";
import { useDrawer } from "@/components/Drawer";
import Toolbar from "@/components/ViewComponents/Toolbar";
import { TransferPatient } from "@/components/ViewComponents/TransferPatient";
import { useNavigate, useLocation } from "react-router";
interface PatientBasic {
	patientId: string;
	patCardno: string;
}
export default function medical_examination() {
	const navigate = useNavigate();
	const { t } = useTranslation();
	const { state } = useLocation();
	const servicesList = useRef([]);
	const columnsService: BasicColumn[] = [
		{
			title: t("felix_ui.sq_numb"),
			width: 100,
			dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t("felix_ui.cli_name"),
			dataIndex: "svcName"
		},
		{
			title: t("kevin_ui.serviceCode"),
			dataIndex: "svcCode"
		},
		{
			title: t("kevin_ui.price"),
			dataIndex: "svcPrice"
		},
		{
			title: t("kevin_ui.specifications"),
			dataIndex: "svcSpeci"
		}

		// {
		// 	title: t("felix_ui.add"),
		// 	fixed: "right",
		// 	width: 100,
		// 	render: (text, record) => {
		// 		return (
		// 			<Button type="link" onClick={addCliFn(record)}>
		// 				{t("felix_ui.add")}
		// 			</Button>
		// 		);
		// 	}
		// }
	];
	const columnsPatientService: BasicColumn[] = [
		{
			title: t("felix_ui.print_result"),
			width: 100,
			dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t("felix_ui.service"),
			width: 100,
			dataIndex: "svcName"
		},
		// {
		// 	title: t("felix_ui.unit"),
		// 	width: 100,
		// 	dataIndex: "svcSpeci"
		// },
		// {
		// 	title: t("felix_ui.quantity"),
		// 	width: 100,
		// 	dataIndex: "svcPrice"
		// },
		{
			title: t("felix_ui.crazy_order"),
			width: 100,
			dataIndex: "createdTime",
			customRender: ({ text }: { text: string }) => {
				return useRender.renderDate(text);
			}
		},
		{
			title: t("felix_ui.sample_at"),
			width: 100,
			dataIndex: "updatedTime",
			customRender: ({ text }: { text: string }) => {
				return useRender.renderDate(text);
			}
		},
		{
			title: t("felix_ui.results_at"),
			width: 100,
			dataIndex: "createdTime",
			customRender: ({ text }: { text: string }) => {
				return useRender.renderDate(text);
			}
		},
		{
			title: t("felix_ui.status"),
			dataIndex: "svcStatus",
			render: (text, record) => {
				return record.status !== 0 ? <Tag color="success">Finished</Tag> : <Tag color="error">UnFinished</Tag>;
			}
		},
		{
			title: t("felix_ui.minute"),
			width: 100,
			dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t("felix_ui.cli_name"),
			width: 100,
			dataIndex: "deptId"
		}
	];
	const formSchemaRight: FormSchema[] = [
		{
			label: t("felix_ui.primary_diagnosis"),
			field: "dxIcdAssociated",
			component: "Input",
			colProps: { span: 6 }
		},
		{
			field: "dxIcdAssociatedName",
			component: "Input",
			colProps: { span: 18 }
		},
		{
			label: t("felix_ui.comorbidities") + " 1",
			field: "dxIcdPrimary1",
			component: "Input",
			colProps: { span: 6 }
		},
		{
			field: "dxIcdPrimary1Name",
			component: "Input",
			colProps: { span: 18 }
		},
		{
			label: t("felix_ui.comorbidities") + " 2",
			field: "dxIcdPrimary2",
			component: "Input",
			colProps: { span: 6 }
		},
		{
			field: "dxIcdPrimaryName",
			component: "Input",
			colProps: { span: 18 }
		},
		{
			label: t("felix_ui.comorbidities") + " 3",
			field: "dxIcdPrimary3",
			component: "Input",
			colProps: { span: 6 }
		},
		{
			field: "dxIcdPrimary3Name",
			component: "Input",
			colProps: { span: 18 }
		},
		{
			label: t("felix_ui.comorbidities") + " 4",
			field: "dxIcdPrimary4",
			component: "Input",
			colProps: { span: 6 }
		},
		{
			field: "dxIcdPrimary4Name",
			component: "Input",
			colProps: { span: 18 }
		},
		// {
		// 	label: "doctorAdvice",
		// 	field: "doctorAdvice",
		// 	component: "InputTextArea",
		// 	componentProps: {
		// 		placeholder: t("kevin_ui.doctorsAdvice")
		// 	}
		// },
		{
			label: "rxDiagnosis",
			field: "rxDiagnosis",
			component: "InputTextArea",
			colProps: { span: 24 },
			componentProps: {
				placeholder: t("kevin_ui.resultOrReport")
			}
		}
	];
	const [rxId, setRxId] = useState("");
	const [patCardno, setPatCardno] = useState("");
	const patientInfoRef = useRef<PatientBasic>({
		patientId: "",
		patCardno: ""
	});

	const [formRight, { validateFields }] = useForm({
		schemas: formSchemaRight,
		labelWidth: 120
	});
	const [patServicesTable] = useTable({
		api: servicesPage,
		columns: columnsService,
		maxHeight: 200,
		rowSelection: {
			type: "checkbox",
			onChange: (_: any, record: any) => {
				console.log(record);
				servicesList.current = record;
			}
		}
	});

	const [formRightButton, { reload }] = useTable({
		api: servicesPatientPage,
		columns: columnsPatientService,
		maxHeight: 200,
		beforeFetch: (parameter: any) => {
			console.log(parameter);
			return {
				...parameter,
				...patientInfoRef.current
			};
		}
	});

	const [registerTransferDrawer, { openDrawer: openDrawerTransfer }] = useDrawer();

	const staticBtnList = [
		{ key: "save", disabled: true },
		{ key: "be_in_hospital", disabled: true },
		{ key: "prescribe", disabled: true },
		{ key: "transfer", disabled: true }
	];
	const [btnList, setBtnList] = useState<any[]>(staticBtnList);

	/** Function */

	const patientInfoSuccess = (value: any) => {
		if (!value.patientId) {
			message.error(t("kevin_ui.thePatient"));
			return;
		}
		patientInfoRef.current = value;
		reload({ searchInfo: { patientId: value.patientId } });
		setBtnList(staticBtnList.map((item: any) => ({ key: item.key, disabled: patientInfoRef.current.patientId === "" })));
	};

	const handlerToolbarAction = (key: string) => {
		const patientInfo = patientInfoRef.current ? patientInfoRef.current : {};
		switch (key) {
			case "save":
				createPatientDiagnosis();
				break;
			case "be_in_hospital":
				navigate("/ImmigrationDictionary/5.01", {
					state: {
						...patientInfo,
						rxId
					}
				});
				break;
			case "prescribe":
				if (window.location.href.includes("EmergencyDictionaryR1")) {
					navigate("/EmergencyDictionaryR1/4.14.01", {
						state: {
							...patientInfo
						}
					});
				} else {
					navigate("/MedicalExamination/4.14.01", {
						state: {
							...patientInfo
						}
					});
				}
				break;
			case "transfer":
				openDrawerTransfer(true, {
					record: patientInfo
				});
				break;
		}
	};
	useEffect(() => {
		setPatCardno(state?.patCardno);
	}, [state]);
	/** Request */

	const createPatientDiagnosis = async () => {
		let dxIcdPrimary: string[] = [];
		try {
			const formValue: Recordable<string> = await validateFields();
			dxIcdPrimary = Object.keys(formValue)
				.filter((ele: string) => ele.length === "dxIcdPrimary".length + 1 && ele.includes("dxIcdPrimary"))
				.map((key: string) => formValue[key]);
			const res = await diagnosisCreate({
				dxIcdAssociated: formValue.dxIcdAssociated,
				dxIcdPrimary: JSON.stringify(dxIcdPrimary),
				rxDiagnosis: formValue.rxDiagnosis,
				patientId: patientInfoRef.current.patientId
			});
			console.log(res);
			setRxId(res.data);
			message.success("success");
		} catch (err) {
			message.error("fail");
		}
	};

	const patServices = async () => {
		const res = await patServicesBatchcreate({
			svcType: 0,
			...patientInfoRef.current,
			services: servicesList.current
		});
		if (!res) return message.error(t("kevin_ui.addFailed"));
		reload();
		message.success(t("kevin_ui.addedSuccessfully"));
		console.log(res);
	};
	return (
		<div className="medical_examination page">
			<div className="page-content">
				<div className="block">
					<PatientInformation patCardno={patCardno} successFn={patientInfoSuccess} />
				</div>
				<div className="medical_examination_content flex space-between mt-2">
					<div className="medical_examination_left">
						<div className="block">
							<div className="block-label  flex space-between">
								<p>Ⅱ.{t("kevin_ui.serviceList")} </p>{" "}
								<Button type="primary" onClick={patServices}>
									{t("task.todo.submit")}
								</Button>
							</div>
							<BasicTable register={patServicesTable}></BasicTable>
						</div>
						<div className="block mt-2">
							<div className="block-label">Ⅲ.{t("kevin_ui.patientServices")}</div>
							<BasicTable className="mt-2" register={formRightButton}></BasicTable>
						</div>
					</div>
					<div className="medical_examination_right block ml-2">
						<div className="block-label">Ⅳ.{t("felix_ui.info_out")}</div>
						<BasicForm register={formRight}></BasicForm>
					</div>
				</div>
			</div>
			<Toolbar btnList={btnList} action={handlerToolbarAction} />
			<TransferPatient register={registerTransferDrawer}></TransferPatient>
		</div>
	);
}
